package com.xgc.book.bookserver.util.shiro;

import com.xgc.book.bookserver.bean.TokenBean;
import com.xgc.book.bookserver.bean.UserinfoBean;
import com.xgc.book.bookserver.bean.VipBean;
import com.xgc.book.bookserver.bean.VipTokenBean;
import com.xgc.book.bookserver.service.TokenService;
import com.xgc.book.bookserver.service.UserinfoService;
import com.xgc.book.bookserver.service.VipService;
import com.xgc.book.bookserver.service.VipTokenService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author PangJunjie
 * @Date 2023/11/21/021
 */
@Component
public class Shiro2Realm extends AuthorizingRealm {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserinfoService userinfoService;
    @Autowired
    private VipTokenService vipTokenService;
    @Autowired
    private VipService vipService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return new SimpleAuthorizationInfo();
    }

    /*使自定义token生效*/
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof Shiro2Token;
    }

    /*token验证*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        /*获取token*/
        String token = (String) authenticationToken.getPrincipal();
        /*获取token实体*/
        TokenBean tokenBean = tokenService.getByToken(token);
        Integer loginId = null;
        if (tokenBean == null) {
            VipTokenBean vipTokenBean = vipTokenService.getByToken(token);
            VipBean vipBean = vipService.getById(vipTokenBean.getVipId());
            if (vipBean != null) {
                loginId = vipBean.getVipId();
            }
        } else {
            /*获取用户信息*/
            UserinfoBean userinfoBean = userinfoService.getById(tokenBean.getUserId());
            if (userinfoBean != null) {
                loginId = userinfoBean.getUserId();
            }
        }
        return new SimpleAuthenticationInfo(loginId, token, getName());

    }
}
